package com.myproject.http;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Description: //TODO  简单的HTTP服务器， 其实就是接受HTTP请求，并解析请求，
 * @Author: sunfch
 * @Date: 2019/1/3 16:35
 * @Param:
 * @Return:
 */
public class ServerTest1 {

    public static void main(String[] args) {


        try {

            /*监听端口号，只要是8888就能接收到*/
            ServerSocket serverSocket = new ServerSocket(9960);
            System.out.println("服务器准备就绪~");
            System.out.println("服务器信息："+serverSocket.getInetAddress()+" P: "+serverSocket.getLocalPort());

            while (true){
                Socket socket = serverSocket.accept();
                ClientHandler clientHandler = new ClientHandler(socket);
                clientHandler.start();
                System.out.println(socket.toString()+": accept");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class ClientHandler extends Thread{

        private Socket socket;

        public ClientHandler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {

            try {
                /*获取客户端输入流，就是请求过来的基本信息：请求头，换行符，请求体*/
                InputStream inputStream = socket.getInputStream();
                /**
                 * 接受HTTP请求，并解析数据
                 */

                int b;
                char c;
                while ((b=inputStream.read())!=-1){
                    System.out.println(b);
                }
                System.out.println(b);





                // close
                inputStream.close();
                socket.close();
                System.out.println(socket+": close");
            } catch (Exception e){
                System.err.println(Thread.currentThread().getName()+"连接异常断开"+e.getMessage());
                e.printStackTrace();
            }


        }
    }
}